package nio.buffer;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;

public class BufferTest3 {

	public static void main(String[] args) {
		
		Charset cs = Charset.forName( "UTF-8" );
		
		ByteBuffer buffer = ByteBuffer.allocate( 100 );
		
		System.out.println( buffer );
		
		buffer.putInt( 100 );
		buffer.putLong( 200L );
		
		final byte[] bytes = "高级伴读书童".getBytes( cs ); 
		final int length = bytes.length ;
		buffer.putInt( length ); // 将 字节数组 长度 以 int 形式保存到缓冲区中
		buffer.put( bytes ); // 将整个字节数组保存到缓冲区中
		
		System.out.println( buffer );
		
		// 重绕此缓冲区 : 就是从头再来 ( 并清除标记 )
		buffer.rewind(); // 1、将当前位置修改为开头( position = 0 ; ) 2、清除标记( mark = -1 ; )
		
		System.out.println( buffer );
		
		System.out.println( "~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~" );
		
		System.out.println( buffer.getInt() );
		
		System.out.println( buffer.getLong() );
		
		int len = buffer.getInt();
		
		byte[] dst = new byte[ len ];
		buffer.get( dst );
		String s = new String( dst , cs );
		System.out.println( s );
		
		System.out.println( "~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~" );
		
		System.out.println( buffer );
		
		// 反转此缓冲区 : 
		// 1、以当前位置为限制位置 ( limit = position ; )
		// 2、将当前位置设置为起始位置 ( position = 0 ; )
		// 3、清除标记 ( mark = -1 )
		buffer.flip(); 
		
		System.out.println( buffer );
		
		System.out.println( buffer.getInt() );
		
		System.out.println( buffer.getLong() );
		
		int n = buffer.getInt();
		
		byte[] b = new byte[ n ];
		buffer.get( b );
		String x = new String( b , cs );
		System.out.println( x );
		
		System.out.println( buffer );
		
		// buffer.putInt( 1 ); // BufferOverflowException
		// buffer.get(); // BufferUnderflowException
		
		System.out.println( "~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~" );
		
		System.out.println( buffer );
		
		// 清除此缓冲区:
		// 1、将当前位置设置为起始位置 ( position = 0 ; )
        // 2、将限制位置修改为与缓冲区容量相等( limit = capacity ; )
        // 3、清除标记 ( mark = -1 ; )
		buffer.clear(); // clear 方法并没有清除缓冲区中已经存在的内容
		
		System.out.println( buffer );
		
		System.out.println( buffer.getInt() );
		
		System.out.println( buffer.getLong() );
		
		int m = buffer.getInt();
		
		byte[] t = new byte[ m ];
		buffer.get( t );
		String p = new String( t , cs );
		System.out.println( p );
		

	}

}
